/**
 * Util.java
 */
package com.ndm.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.ndm.common.Const;

/**
 * @author gundallove
 * @email gundallove@gmail.com
 */
public class Util {

	/**
	 * <pre>
	 * 파일 폴더 삭제
	 * @param file
	 * @return
	 * boolean
	 * </pre>
	 */
	public static boolean deleteFileDir(File file) {

		if(!file.exists()) {
			return false;
		}
		return file.delete();
	}

	//폴더 밑의 파일 삭제
	public static boolean deleteFile(String partDir){
		
		File path = new File(partDir);

		try{
	    	String[] children = path.list();
	    	if (children != null) {
		    	for (int i=0; i<children.length; i++) {
		    		String filename = children[i];
		    		File f = new File(partDir + filename);
			    	if (f.exists()) {
			    		f.delete();
			        }
		        }//for
	        }//if
		}catch(Exception e){
			return false;
		}
    	return true;
	}
	
	/*
	 * 디렉토리 생성
	 */
	public static void setMakeDir(String makeDir) {
    	
    	try{
			File dir = new File(makeDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
    	}catch(Exception e){
    		Log.d("mkdirs : ",e.getMessage());
    	}
    	
    }
	
	/**
	 * 이미지 파일 존재
	 * @param file
	 * @return
	 */
	public static boolean isExists(String file) {
    	
		boolean isImage = false;
    	try{
			File dir = new File(file);
			if (dir.exists()) {
				isImage = true;
			}
    	}catch(Exception e){
    	}
    	
    	return isImage;
    }
	
	/**
	 * 널처리및 공백 제거
	 * @param str
	 * @return
	 */
	public static String trim(String str) {
		return str == null ? "" : str.trim();
	}

	/**
	 * 
	 * @param str
	 * @return
	 */
	public static String defaultString(String str , String defaultStr){
		return str == null ? defaultStr : str.trim();	
	}

	/**
	 * 네트윅이 사용 가능한 상태인가 확인
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			Log.w(Util.LOG_TAG, "couldn't get connectivity manager");
		} else {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null && info.getState() == NetworkInfo.State.CONNECTED) {
				Log.i(Util.LOG_TAG, "network is available");
				return true;
			}
		}
		Log.i(Util.LOG_TAG, "network is not available");
		return false;
	}
	
    /**
     * WIFI사용중?
     */
    public static boolean isWifi(Context context) 
    {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    if (connectivity == null) 
	    {
	        Log.w(Util.LOG_TAG, "couldn't get connectivity manager");
	    }
	    else 
	    {
	        NetworkInfo info = connectivity.getActiveNetworkInfo();
	        
	        if (info != null && info.getType() == ConnectivityManager.TYPE_WIFI)
	        	return true;
	    }
	    
	    return false;
    }
	
    public static long stringToLong(String str, long defaultValue) {
        try {
        	if(trim(str).length()==0)
        		return 0;
        	else
        		return Long.parseLong(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }
    
    public static int stringToInt(String str, int defaultValue) {
        try {
        	if(trim(str).length()==0)
        		return 0;
        	else
        		return Integer.parseInt(str);
        } catch (NumberFormatException nfe) {
            return defaultValue;
        }
    }
    
    public static String getCutstring(String param, int len, String tail)
    {
        if(param.length() <= len)
            return param;
        StringCharacterIterator sci = new StringCharacterIterator(param);
        StringBuffer buffer = new StringBuffer();
        buffer.append(sci.first());
        for(int i = 1; i < len; i++)
            if(i < len - 1)
            {
                buffer.append(sci.next());
            } else
            {
                char c = sci.next();
                if(c != ' ')
                    buffer.append(c);
            }

        buffer.append(tail);
        return buffer.toString();
    }
    
    /**
	 * 
	 * @param strImageURL
	 * @return
	 */
	public static Bitmap downBitmap(String strImageURL) 
	{
	    Bitmap imgBitmap = null;
	    
	    try
	    {
	    	URL url = new URL(strImageURL);
	    	URLConnection conn = url.openConnection();
	    	conn.connect();
	    	
	    	int nSize = conn.getContentLength();
	    	BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), nSize);
	    	imgBitmap = Bitmap.createBitmap(BitmapFactory.decodeStream(bis));
	    	
	    	bis.close();
	    }
	    catch (Exception e)
	    {
	    	e.printStackTrace();
	    }
	    
	    return imgBitmap;
	}
	
	
	
	/**
	 * yyyyMMdd Format의 Date 형태로 리턴한다.
	 *
	 * @return 현재날짜를 yyyy-MM-dd 형태로 리턴
	 */
	public static String getDate() {
		Date dt = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd", Locale.KOREA);
		return df.format(dt);
	}
	
	private static final String LOG_TAG = Util.class.getSimpleName();
	
}
